package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.common.redis.RedisConstant;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        Page<Brand> info = new Page<>(page, rows);
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        query().like(isKeyExists, "name", key)
                .or()
                .like(isKeyExists, "letter", key)
                .page(info);
        List<Brand> records = info.getRecords();
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(records));
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long id) {
        List<CategoryBrand> categoryBrands = categoryBrandService.query().eq("category_id", id).list();
        if (CollectionUtils.isEmpty(categoryBrands)) {
            return Collections.emptyList();
        }
        ArrayList<Long> brandIds = new ArrayList<>();
        categoryBrands.forEach(categoryBrand -> brandIds.add(categoryBrand.getBrandId()));
        List<Brand> brands = listByIds(brandIds);
        return BrandDTO.convertEntityList(brands);
    }

    @Transactional
    @Override
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        brandDTO.getCategoryIds().forEach(cid -> categoryBrandService.save(CategoryBrand.of(cid, brand.getId())));
        if (brandDTO.getImage() != null) {
            redisTemplate.opsForSet().add(RedisConstant.BRAND_PIC_DB_RESOURCES, brandDTO.getImage());
        }
    }

    @Transactional
    @Override
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean success = updateById(brand);
        if (!success) {
            throw new LyException(500, "更新品牌失败！");
        }
        success = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        if (!success) {
            throw new LyException(500, "更新品牌失败！删除中间表出错！");
        }
        Long bid = brand.getId();
        brandDTO.getCategoryIds().forEach(cid -> categoryBrandService.save(CategoryBrand.of(cid, bid)));
        if (brandDTO.getImage() != null) {
            redisTemplate.opsForSet().add(RedisConstant.BRAND_PIC_DB_RESOURCES, brandDTO.getImage());
        }
    }

    @Transactional
    @Override
    public void deleteBrand(Long id) {
        boolean success = removeById(id);
        if (!success) {
            throw new LyException(500, "删除品牌失败！");
        }
        success = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        if (!success) {
            throw new LyException(500, "删除品牌失败！删除中间表错误！");
        }
    }
}
